<?php

namespace thinkct\library\draw;

use midjourney\Service;
use app\admin\model\ai\Config as ConfigModel;
use GuzzleHttp\Client;
use app\common\model\ai\draw\Content as drawContentModel;

class Midjourney
{
    protected array $config = [];
    protected Service $midjourney;

    public function __construct()
    {
        $this->config = [
            'channel_id' => ConfigModel::where('name', 'draw_channel_id')->value('value'),
            'oauth_token' => ConfigModel::where('name', 'draw_authorization')->value('value'),
            //'timeout' => ConfigModel::where('name', 'draw_timeout')->value('value'),
            //'application_id' => ConfigModel::where('name', 'draw_application_id')->value('value'),
            //'data_id' => ConfigModel::where('name', 'draw_id')->value('value'),
            //'data_version' => ConfigModel::where('name', 'draw_version')->value('value'),
            //'session_id' => ConfigModel::where('name', 'draw_session_id')->value('value'),
        ];
        $this->midjourney = new Service($this->config);
    }

    // 开始任务
    public function start_task($data): array
    {
        $prompt = $data['prompt'];

        try {
            $result = $this->midjourney->imagine($prompt);
            if ($result->task_id) {
                return [
                    'status' => 1,
                    'msg' => '请求成功',
                    'id' => $result->task_id
                ];
            }
        } catch (\Exception $e) {
            return [
                'status' => 0,
                'msg' => $e->getMessage()
            ];
        }

        return [
            'status' => 0,
            'msg' => '请求失败'
        ];
    }

    public function task_detail($data): array
    {
        $task_id = $data['message_id'];

        try {
            $response = $this->midjourney->getImagine($task_id);
            // 没有完成的任务task_id存在 为null
            if (!empty($response['task_id'])) {

                $url = $response['raw_message']['attachments'][0]['url'] ?? '';

                if (empty($url)) {
                    return [
                        'status' => 0,
                        'id' => $task_id,
                        'progress' => 15, // 进度条
                    ];
                } else {


                    // 通过Client获取图片
                    $client = new Client([
                        'verify' => false,
                    ]);
                    $response = $client->get($url);
                    $image = $response->getBody()->getContents();
                    //die(var_dump($image));


                    //$image = file_get_contents($url);


                    // 保存图片到本地
                    $path = '/storage/ai/draw/'.time().'.png';
                    // 创建目录
                    if(!is_dir(root_path() . '/public/storage/ai/draw/')) {
                        mkdir(root_path() . '/public/storage/ai/draw/', 0777, true);
                    }
                    file_put_contents(root_path() . 'public/' . $path, $image);

                    $drawContent = drawContentModel::where('message_id', $task_id)->find();
                    $drawContent->image = $path;
                    $drawContent->is_draw = 1;
                    $drawContent->save();


                    return [
                        'status' => 1,
                        'id' => $task_id,
                        'progress' => 100,
                        'url' => $path,
                    ];
                }
            }
            return [
                'status' => 0,
                'progress' => 15, // 进度条
                'msg' => '绘画加载中...'
            ];
        } catch (\Exception $e) {
            return ['status'=>2, 'msg'=>$e->getMessage()];
        }
    }
}